# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.encoding import smart_str
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.shortcuts import render_to_response

from werobot.utils import _check_signature
from .utils import create_reply
from operator import itemgetter

import requests

def check_signature(request):
    signature = request.GET.get('signature', None)
    timestamp = request.GET.get('timestamp', None)
    nonce = request.GET.get('nonce', None)
    token = settings.TOKEN
    
    return _check_signature(signature, token, timestamp, nonce)

@csrf_exempt
def weixin(request):
    if request.method == 'GET':
        if check_signature(request):
            return HttpResponse(request.GET.get("echostr", None))
        raise PermissionDenied
    else:
        if check_signature(request):
            xml = smart_str(request.body)
            reply_xml = create_reply(xml)
            return HttpResponse(reply_xml)
        raise PermissionDenied
        
def create_menu(request):
    import utils
    res = utils.create_menu(settings.APPID, settings.SECRET, settings.MENU_DATA)
    if res == None:
        x = "成功创建自定义菜单!"
    else:
        x = res
    return HttpResponse(x)


def input_parcel(request):
    return render_to_response('input_parcel.html')

@csrf_exempt
def query_parcel(request):
    if request.method == 'POST' and request.POST['fname']:
        waybill_no=request.POST['fname']

        url= "http://202.105.44.4/chinapost/postMailAction!ajaxQuery.do?mailNo="
        tux_url = url + "%s" % (waybill_no)
        r = requests.get(tux_url)     
        r.encoding='utf-8'    
        res = r.json()

        if not res or res == u"邮件号码格式错误":

            message="邮件编号可能输错了!"
            return render_to_response('input_parcel.html',{
                        'message': message,
                    })
        else:
            #y = res['redo'][0]['d4496_mail_last_brch']  
            if res['redo']:
                items = sorted(res['redo'],key=itemgetter('d44_70_tran_date'), reverse=True) 
                return render_to_response('show_parcel.html',{
                          'items':items,
                           })
    else:
        message="请输入邮件编号!"
        return render_to_response('input_parcel.html',{
                        'message': message,
                    })
        
def more_serve(request):
    return render_to_response('more_serve.html')

def postage(request):
    return render_to_response('postage.html')
    
